package study2018.com.xtianzhuang.www.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: TwoThread
 * @author : xtian.zhuang
 * @date 2018年7月20日 上午9:26:20
 *
 */
public class TwoThread {
	/**
	 * 开始数
	 */
	private int start = 1;

	private boolean flag = false;

	private static final Lock lock = new ReentrantLock();

	public static void main(String[] args) {
		TwoThread twoThread = new TwoThread();

		Thread t1 = new Thread(new Thread1(twoThread));
		t1.setName("t1");

		Thread t2 = new Thread(new Thread2(twoThread));
		t2.setName("t2");

		t1.start();
		t2.start();
	}

	/**
	 * function: 奇数线程
	 * 
	 * @ClassName: Thread1
	 * @author : xtian.zhuang
	 * @date 2018年7月20日 上午9:27:36
	 *
	 */
	public static class Thread1 extends Thread {
		private TwoThread twoThread;

		public Thread1(TwoThread twoThread) {
			this.twoThread = twoThread;
		}
		public void run() {
			while(twoThread.start<=100){
				if(twoThread.flag){
					try {
						lock.lock();
						System.out.println(Thread.currentThread().getName() + "---" + twoThread.start);
						twoThread.start++;
						twoThread.flag = false;
						
					} finally {
						// TODO: handle finally clause
						lock.unlock();
					}
				}else{
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		}
	}

	/**
	 * function:偶数线程
	 * 
	 * @ClassName: Thread2
	 * @author : xtian.zhuang
	 * @date 2018年7月20日 上午9:28:26
	 *
	 */
	public static class Thread2 extends Thread {
		private TwoThread twoThread;

		public Thread2(TwoThread twoThread) {
			this.twoThread =twoThread;
		}
		public void run() {
			while (twoThread.start <= 100) {
				if (!twoThread.flag) {
					try {
						lock.lock();
						System.out.println(Thread.currentThread().getName() + "---" + twoThread.start);
						twoThread.start++;
						twoThread.flag = true;
					} finally {
						// TODO: handle finally clause
						lock.unlock();
					}
				} else {
					try {
						Thread.sleep(10);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		}
	}
}
